package com.banciyuan.bcywebview.biz.apprecommend;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.TagApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.tag.FlowView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.FollowTag;

/**
 * Created by squall on 2017/3/6.
 */

public class RecommendNewTagActivity extends BaseActivity {

    private TextView tvTitle;
    private TextView tvTitleSencond;
    private FlowView tags;
    private TextView next;
    private Gson gson;
    private RequestQueue queue;
    private PopupWindow mPopWindow;
    private ProgressBar pbIng;
    private ImageView ivDone;
    private TextView tvDesc;
    private TextView select_nums;

    private Map<String, String> followTags = new HashMap<>();
    private List<FollowTag> flist = new ArrayList<>();
    private boolean havefollow;
    private int followCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recommend_tag_activity);
        initArgs();
        initUi();
        initData();
        initAction();
    }

    @Override
    protected void initArgs() {
        gson = new Gson();
        queue = VolleyQueue.getRquest(this);
    }

    @Override
    public void onBackPressed() {

    }

    @Override
    protected void initUi() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitleSencond = (TextView) findViewById(R.id.tv_title_sencond);
        tags = (FlowView) findViewById(R.id.tags_area);
        next = (TextView) findViewById(R.id.tv_next_step);
        select_nums = (TextView) findViewById(R.id.select_nums);
        select_nums.setVisibility(View.VISIBLE);

        tvTitle.setText(getString(R.string.hottag_title));
        tvTitleSencond.setText(getString(R.string.cp_bonus));

        tags.getLayoutTransition().setDuration(150);
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + TagApi.getHotSubFollow();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    flist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<FollowTag>>() {
                    }.getType());
                    checkFollow();
                    checkSelect();
                    renderData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        };
        Map<String, String> map = HttpUtils.getData(pairs);
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(stringRequestParam);
    }

    private void renderData() {
        tags.removeAllViews();
        List<Integer> ilist = new ArrayList<>();
        for (int i = 0; i < flist.size(); i++) {
            TextView tag = (TextView) View.inflate(this, R.layout.recommend_tag, null);
            final FollowTag f = flist.get(i);

            if (f.isTf_status()) {
                tag.setSelected(true);
                if (f.getRela_tags() != null && !f.getRela_tags().isEmpty()) {
                    ilist.add(flist.indexOf(f));
                }
            }
            if (!TextUtils.isEmpty(f.getTag_name())) {
                tag.setText(f.getTag_name());
            }
            final String tag_id = f.getTag_id();
            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setSelected(!v.isSelected());
                    if (v.isSelected()) {
                        followCount++;
                    } else {
                        followCount--;
                    }
                    followTags.put(tag_id, v.isSelected() ? "follow" : "unfollow");
                    addChild(f.getRela_tags(), flist.indexOf(f));
                    checkSelect();
                }
            });
            tags.addView(tag);
        }

        int length = 0;
        for (int i = 0; i < ilist.size(); i++) {
            int index = ilist.get(i);
            length += addChild(flist.get(index + length).getRela_tags(), index + length);
        }
    }

    private void checkSelect() {
        if (followCount < 1) {
            next.setSelected(false);
        } else {
            next.setSelected(true);
        }
        select_nums.setText(String.format(getString(R.string.select_recommend), 1, followCount));
    }

    private int addChild(final List<FollowTag> childlist, int index) {
        childlist.removeAll(flist);
        flist.addAll(index, childlist);

        for (final FollowTag f : childlist) {
            TextView tag = (TextView) View.inflate(this, R.layout.recommend_tag, null);
            if (f.isTf_status()) {
                tag.setSelected(true);
            }
            if (!TextUtils.isEmpty(f.getTag_name())) {
                tag.setText(f.getTag_name());
            }
            final String tag_id = f.getTag_id();
            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setSelected(!v.isSelected());
                    if (v.isSelected()) {
                        followCount++;
                    } else {
                        followCount--;
                    }
                    followTags.put(tag_id, v.isSelected() ? "follow" : "unfollow");
                    checkSelect();
                }
            });
            tags.addView(tag, index + 1);
        }
        return childlist.size();
    }

    private void checkFollow() {
        for (FollowTag f : flist) {
            if (f.isTf_status()) {
                havefollow = true;
                followCount++;
            }
            for (FollowTag f2 : f.getRela_tags()) {
                if (f2.isTf_status()) {
                    havefollow = true;
                    followCount++;
                }
            }
        }
        if (!havefollow && flist != null && flist.size() > 0) {
            flist.get(0).setTf_status(true);
            followTags.put(flist.get(0).getTag_id(), "follow");
            followCount++;
        }
    }


    private void doLikes() {
        if (!followTags.keySet().isEmpty()) {
            doPop();
            String url = HttpUtils.BASE_URL + TagApi.getMultifollow();
            List<BcyPair> pairs = new ArrayList<>();
            pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
            pairs.add(new BcyPair(HttpUtils.UPLOAD_DATA, gson.toJson(followTags)));

            Response.Listener<String> onSucc = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    showcomplate();
                }
            };

            Response.ErrorListener onError = new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    showcomplate();
                }
            };

            Map<String, String> map = HttpUtils.getData(pairs);
            StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
            queue.add(stringRequestParam);
        } else {
            gotoUtil.gotoAct(RecommendNewTagActivity.this, RecommendPersonNewActivity.class);
            finish();

        }
    }

    private void showcomplate() {
        pbIng.setVisibility(View.INVISIBLE);
        ivDone.setVisibility(View.VISIBLE);
        tvDesc.setText(getString(R.string.done_success));
        next.postDelayed(new Runnable() {
            @Override
            public void run() {
                gotoUtil.gotoAct(RecommendNewTagActivity.this, RecommendPersonNewActivity.class);
                finish();
            }
        }, 500);
    }


    @Override
    protected void initAction() {
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (followCount >= 1) {
                    doLikes();
                } else {
                    MyToast.show(RecommendNewTagActivity.this, String.format(getString(R.string.select_recommend), 1, followCount));
                }
            }
        });
    }

    private void doPop() {
        View contentView = View.inflate(this, R.layout.pop_mark_acg, null);
        mPopWindow = new PopupWindow(contentView,
                -1, -1,
                true);
        pbIng = (ProgressBar) contentView.findViewById(R.id.pb_ing);
        ivDone = (ImageView) contentView.findViewById(R.id.iv_done);
        tvDesc = (TextView) contentView.findViewById(R.id.tv_desc);
        mPopWindow.setContentView(contentView);
        mPopWindow.setOutsideTouchable(false);
        mPopWindow.showAtLocation(tags, Gravity.LEFT + Gravity.TOP,
                0, 0);
    }


}
